package com.wc5818.wcComOrder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiniu.util.Auth;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.wc5818.bankSearch.entity.BankReport;
import com.wc5818.bankSearch.mapper.BankReportMapper;
import com.wc5818.chuShen.entity.FirstAuditReport;
import com.wc5818.chuShen.mapper.FirstAuditReportMapper;
import com.wc5818.common.AjaxResult;
import com.wc5818.dto.CurrentActiveItem;
import com.wc5818.dto.WcComOrderEx;
import com.wc5818.gongzdc.entity.WorkReport;
import com.wc5818.gongzdc.mapper.WorkReportMapper;
import com.wc5818.service.WorkflowService;
import com.wc5818.utils.QiniuCloudUtil;
import com.wc5818.wcBasicInfo.entity.WcBasicInfo;
import com.wc5818.wcBasicInfo.mapper.WcBasicInfoMapper;
import com.wc5818.wcCarInfos.entity.WcCarInfos;
import com.wc5818.wcCarInfos.mapper.WcCarInfosMapper;
import com.wc5818.wcComOrder.dto.HistoryProcessDto;
import com.wc5818.wcComOrder.entity.WcComOrder;
import com.wc5818.wcComOrder.mapper.WcComOrderMapper;
import com.wc5818.wcComOrder.service.IWcComOrderService;
import com.wc5818.wcDanbrInfo.entity.WcDanbrinfo;
import com.wc5818.wcDanbrInfo.mapper.WcDanbrinfoMapper;
import com.wc5818.wcFlow.entity.WcFlow;
import com.wc5818.wcFlow.mapper.WcFlowMapper;
import com.wc5818.wcFlow.service.IWcFlowService;
import com.wc5818.wcImgPath.entity.WcImgPath;
import com.wc5818.wcImgPath.mapper.WcImgPathMapper;
import com.wc5818.wcOrderDetail.entity.WcOrderDetail;
import com.wc5818.wcOrderDetail.service.IWcOrderDetailService;
import com.wc5818.wcSysUser.entity.WcSysUser;
import com.wc5818.wcSysUser.mapper.WcSysUserMapper;
import com.wc5818.wcSysUser.service.IWcSysUserService;
import com.wc5818.wcWorkInfo.entity.WcWorkInfo;
import com.wc5818.wcWorkInfo.mapper.WcWorkInfoMapper;
import com.wc5818.wcWorkflowChulr.entity.WcWorkflowChulr;
import com.wc5818.wcWorkflowChulr.mapper.WcWorkflowChulrMapper;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.task.Task;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-15
 */
@RestController
@RequestMapping("/wcComOrder")
public class WcComOrderController {
    @Autowired
    IWcComOrderService wcComOrderService;
    @Autowired
    IWcOrderDetailService iWcOrderDetailService;
    @Autowired
    WcComOrderMapper wcComOrderMapper;
    @Autowired
    WcWorkflowChulrMapper wcWorkflowChulrMapper;
    @Autowired
    WorkflowService workflowService;
    @Autowired
    WcFlowMapper wcFlowMapper;
    @Autowired
    IWcFlowService wcFlowService;

    @Autowired
    WcSysUserMapper wcSysUserMapper;

    private static String getString(int t){
        String m="";
        if(t>0){
            if(t<10){
                m="0"+t;
            }else{
                m=t+"";
            }
        }else{
            m="00";
        }
        return m;
    }

    /**
     *
     * @param t 毫秒
     * @return
     * @author Peter（张春玲）
     */
    public static String format(int t){
        if(t<60000){
            return (t % 60000 )/1000+"秒";
        }else if((t>=60000)&&(t<3600000)){
            return getString((t % 3600000)/60000)+":"+getString((t % 60000 )/1000);
        }else {
            return getString(t / 3600000)+":"+getString((t % 3600000)/60000)+":"+getString((t % 60000 )/1000);
        }
    }

    @Autowired
    IWcFlowService iWcFlowService;

    @GetMapping("/myHistoryProcess")
    public Object myHistoryProcess(String userId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        WcFlow wcFlow = iWcFlowService.getOne(new QueryWrapper<WcFlow>().eq("userId", userId).eq("isEnd", 0), false);
        if(wcFlow == null) {
            ajaxResult.setErrorMsg("查询流程id失败");
            return ajaxResult;
        }

        String[] tmp = wcFlow.getProcessId().split(";");
        List<CurrentActiveItem> list = workflowService.assembleList(tmp[0], tmp[1]);

        ajaxResult.setSuccess(true);
        ajaxResult.setData(list);
        return ajaxResult;
    }
    
    @GetMapping("/myTaskList")
    public Object myTaskList(String userId) {
        return workflowService.taskList(userId);
    }

    @GetMapping("/myTaskList4History")
    public Object myTaskList4History(String userId) {
        return workflowService.taskList4History(userId);
    }

    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public Object addOrder(@RequestBody WcComOrder wcComOrder) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        if (wcComOrderService.selectWcComOrderUserID(wcComOrder.getUserId())) {
            SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String strDate = sfDate.format(new Date());
            //为了防止高并发重复,再获取3个随机数
            String random = getRandom(3);
            String orderNum = strDate + random;
            wcComOrder.setOrdernum(orderNum);
            wcComOrder.setCreateTime(LocalDateTime.now());
            wcComOrder.setUpdateTime(LocalDateTime.now());
            wcComOrderService.addWCComOrder(wcComOrder);

            WcOrderDetail wcOrderDetail = new WcOrderDetail();
            wcOrderDetail.setOrderId(orderNum);
            wcOrderDetail.setAmount(1);
            iWcOrderDetailService.addWcOrderDetail(wcOrderDetail);

            WcWorkflowChulr wcWorkflowChulr = wcWorkflowChulrMapper.selectOne(new QueryWrapper<WcWorkflowChulr>().eq("yewyId", wcComOrder.getParentUserId()));
            if (wcWorkflowChulr != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("ordernum", orderNum);

                map.put("yewyId", wcWorkflowChulr.getYewyId());
                map.put("chesId", wcWorkflowChulr.getChesId());
                map.put("yunyzxId", wcWorkflowChulr.getYunyzxId());
                map.put("fengkId", wcWorkflowChulr.getFengkzxId());
                map.put("cheyId", wcWorkflowChulr.getCheysId());
                map.put("chewId", wcWorkflowChulr.getChewsId());

                map.put("endProcess", false);
                map.put("chesReject2Yewy", false);
                map.put("yunyzxReject2Yewy", false);
                map.put("fengkzxReject2Yewy", false);

                String processId = workflowService.startNewProcess("万车万融_贷款产品审核流程_003", map);
                WcFlow wcFlow = new WcFlow();
                wcFlow.setOrdernum(orderNum);
                wcFlow.setUserId(wcComOrder.getUserId());
                wcFlow.setProcessId(processId);
                wcFlow.setIsEnd(0);

                if(wcFlowService.save(wcFlow))
                    ajaxResult.setSuccess(true);
            }
        }

        return ajaxResult;
    }

    @GetMapping("/complete")
    public Object complete(Boolean pass, String taskId, String comment) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        Map<String, Object> map = new HashMap<>();
        map.put("comment", comment);
        map.put("chewId", "1000117");
        if(!pass)
            map.put("endProcess", true);

        try {
            workflowService.complete(taskId, map);
            ajaxResult.setSuccess(true);

        } catch (Exception error) {
            ajaxResult.setErrorMsg(error.getMessage());
        }

        return ajaxResult;
    }

    /**
     * ke7MrFXqZnJ3BxbOkGnPogJBvIhDT2-69qYaxumQ:C8FFD4rUTsd9QLY9Z1iAxfwRJcA=:eyJzY29wZSI6IndjLXd4LWltZyIsInJldHVybkJvZHkiOiJ7XCJmaWxlVXJsXCI6XCJpbWcud2M1ODE4LmNvbSR7a2V5fVwifSIsImRlYWRsaW5lIjoxNTgyMTI4NDUzfQ==
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getToken")
    public @ResponseBody
    Map<String, String> getToken() throws IOException {

        Map<String, String> map = new HashMap<String, String>();
        map.put("uptoken", QiniuCloudUtil.getupToken());
        return map;
    }

    @GetMapping("/getOrderNum")
    public Object getOrderNum(String orderNum) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);
        WcComOrder wcComOrder = wcComOrderMapper.selectOne(new QueryWrapper<WcComOrder>().eq("ordernum", orderNum));
        if (wcComOrder != null) {
            ajaxResult.setData(wcComOrder);
            ajaxResult.setSuccess(true);
        }
        return ajaxResult;
    }

    /**
     * 根据用户名username 和 forbyusername
     * 获取 相关数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "getWCComOrderForUserNameOrForbyusername", method = RequestMethod.GET)
    public List<WcComOrder> getWCComOrderForUserNameOrForbyusername(String forbyusername, String parentUserId) {
        return wcComOrderService.selectListwcComOrder(forbyusername, parentUserId);
    }

    @Autowired
    WcBasicInfoMapper wcBasicInfoMapper;

    @Autowired
    WcWorkInfoMapper wcWorkInfoMapper;

    @Autowired
    WcDanbrinfoMapper wcDanbrinfoMapper;

    @Autowired
    WcCarInfosMapper wcCarInfosMapper;

    @Autowired
    WcImgPathMapper wcImgPathMapper;

    @Autowired
    FirstAuditReportMapper firstAuditReportMapper;

    @Autowired
    BankReportMapper bankReportMapper;

    @Autowired
    WorkReportMapper workReportMapper;

    WcComOrderEx getCompleteState(String orderId) {
        WcComOrderEx wcComOrderEx = new WcComOrderEx();

        List list = wcBasicInfoMapper.selectList(new QueryWrapper<WcBasicInfo>().eq("orderId", orderId).orderByDesc("caretdata"));
        if(list != null  && list.size() > 0)
            wcComOrderEx.setBaseInfoComplete(true);

        list = wcWorkInfoMapper.selectList(new QueryWrapper<WcWorkInfo>().eq("orderId", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setWorkInfoComplete(true);

        list = wcDanbrinfoMapper.selectList(new QueryWrapper<WcDanbrinfo>().eq("orderNum", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setRecognizorComplete(true);

        list = wcCarInfosMapper.selectList(new QueryWrapper<WcCarInfos>().eq("orderId", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setCarInfoComplete(true);

        list = wcImgPathMapper.selectList(new QueryWrapper<WcImgPath>().eq("orderId", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setPictureComplete(true);

        list = firstAuditReportMapper.selectList(new QueryWrapper<FirstAuditReport>().eq("orderNum", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setFirstAuditComplete(true);

        list = bankReportMapper.selectList(new QueryWrapper<BankReport>().eq("orderNum", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setBankComplete(true);

        list = workReportMapper.selectList(new QueryWrapper<WorkReport>().eq("orderNum", orderId));
        if(list != null && list.size() > 0)
            wcComOrderEx.setWorkCompanyComplete(true);

        return wcComOrderEx;
    }

    /**
     * 根据userid查详细信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getWcComOrderForUserId")
    public Object getWcComOrderForUserId(@RequestParam("userId") Integer userId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        WcComOrder wcComOrderUserID = wcComOrderService.getWcComOrderUserID(userId);
        if (wcComOrderUserID != null) {

            WcComOrderEx wcComOrderEx = getCompleteState(wcComOrderUserID.getOrdernum());
            if(wcComOrderEx != null)
                BeanUtils.copyProperties(wcComOrderUserID, wcComOrderEx);

            ajaxResult.setSuccess(true);
            ajaxResult.setData(wcComOrderEx);

            return ajaxResult;
        }

        return ajaxResult;
    }

    @PostMapping("/updateWcComOrderStatus")
    public Boolean updateWcComOrderStatus(Integer userId, String status) {
        return wcComOrderService.updateWcComOrderStatus(userId, status);
    }

    /**
     * 随机数
     *
     * @param length
     * @return
     */
    public static String getRandom(Integer length) {
        String result = "";
        Random rand = new Random();
        int n = 20;
        if (null != length && length > 0) {
            n = length;
        }
        int randInt = 0;
        for (int i = 0; i < n; i++) {
            randInt = rand.nextInt(10);
            result += randInt;
        }
        return result;
    }
}
